package com.wbt.bambootown;

import android.app.Application;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.wbt.bambootown.api.LoggerInterceptor;
import com.wbt.bambootown.cons.Cons;
import com.wbt.bambootown.entity.Farms;
import com.wbt.bambootown.entity.User;
import com.wbt.bambootown.okhttp.OkHttpUtils;
import com.wbt.bambootown.receiver.NetworkBroadcastReceiver;
import com.wbt.bambootown.receiver.SignalRService;
import com.wbt.bambootown.utils.SPUtils;

import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

public class FrameApp extends Application {
    private static FrameApp mInstance;
    public static User user;
    public static Farms farm;

    public static int currentFarmId;
    public static int currentFacilityId;
    public static int currentDevicesId;

    public static SignalRService mService;


    @Override
    public void onCreate() {
        super.onCreate();
        //Retrofit上传文件不如OkHttpUtils简便
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();

        OkHttpUtils.initClient(client);

        mInstance = this;
        initSpUtils();
    }

    public static void loadUser(){
        user = SPUtils.loadUser();
    }

    public static void loadFarm(){
        farm = SPUtils.loadFarm();
    }

    private void initSpUtils() {
        SPUtils.init(this, Cons.SPCons.SP_NAME);
    }

    public static FrameApp  getApplication(){
        return mInstance;
    }

    public static void logout(){
        SPUtils.saveUser(null);
        user = null;
    }

    // 设置全局替换的 BaseUrl
    public static void btnSetGlobalUrl(String newUrl){
        //当你项目中只有一个 BaseUrl, 但需要动态切换 BaseUrl 时, 全局 BaseUrl 显得非常方便
        //使用 RetrofitUrlManager.getInstance().setUrlNotChange(url); 方法处理过的 url 地址进行网络请求
        //则可以使此 url 地址忽略掉本框架的所有更改效果
        HttpUrl httpUrl = RetrofitUrlManager.getInstance().getGlobalDomain();
        if (null == httpUrl || !httpUrl.toString().equals(newUrl)){
            RetrofitUrlManager.getInstance().setGlobalDomain(newUrl);
        }
    }

}
